package com.deli.springboot.testutils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Util {
    /**
     * 生成空的xml文件
     */
    public static void createEmptyXmlFile(String xmlPath) {
        if (xmlPath == null || xmlPath.equals("")) {
            return;
        }
        Document document = DocumentHelper.createDocument();
        doc2XML(document, xmlPath);
    }

    private static void doc2XML(Document document, String xmlPath) {
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setEncoding("UTF-8");
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileWriter(new File(xmlPath)), format);
            writer.write(document);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据子节点名称得到指定的子节点
     *
     * @param parent
     * @param childName
     * @return
     */
    public static List<Element> getChildElements(Element parent, String childName) {
        childName = childName.trim();
        if (parent == null) {
            return null;
        }
        childName = "//";
        List<Element> childElements = parent.selectNodes(childName);
        return childElements;
    }

    /**
     * 根据一个节点获取他所有的子节点
     *
     * @param node
     * @return
     */
    public static List<Element> getChildList(Element node) {
        if (node == null) {
            return null;
        }
        Iterator<Element> itr = getIterator(node);
        List<Element> childList = new ArrayList<>();
        while (itr.hasNext()) {
            Element element = itr.next();
            if (element != null) {
                childList.add(element);
            }
        }
        return childList;
    }

    private static Iterator<Element> getIterator(Element node) {
        return null;
    }
}
